import subprocess
import rrd_base
import re
import time

import color

try:
    from pyrrd.rrd import DataSource, RRA, RRD
    from pyrrd.graph import DEF, CDEF, VDEF
    from pyrrd.graph import LINE, AREA, GPRINT
    from pyrrd.graph import ColorAttributes, Graph
    import urllib2
    import json
except:
    print "Couldn't load required modules. You probably need to install it with:"
    sys.exit('sudo apt-get install python-pyrrd python-pysnmp4')

class RrdWeather(rrd_base.RrdBase):
    def __init__(self, domain, name):
        super(RrdWeather,self).__init__(domain=domain, group="environment", instance=name)

    def create_file(self):
        dataSources = []
        for ds in ['temperature', 'humidity', 'pressure', 'dewpoint' ]:
            dataSources.append(DataSource( dsName=ds, dsType='GAUGE', heartbeat=self.heartbeat()))

        roundRobinArchives = []
        for func in ['AVERAGE', 'MAX', 'MIN']:
            for step,row in self.rra_pattern():
                roundRobinArchives.append(RRA(cf=func, xff=0.5, steps=step, rows=row))

        self.myRRD = RRD(self.filename, ds=dataSources, rra=roundRobinArchives, step=self.data_step())
        self.myRRD.create()

    def graph(self):
        d     = DEF(rrdfile=self.myRRD.filename, vname='d0', dsName='temperature', cdef="AVERAGE")
        d_max = DEF(rrdfile=self.myRRD.filename, vname='d1', dsName='temperature', cdef="MAX")
        d_min = DEF(rrdfile=self.myRRD.filename, vname='d2', dsName='temperature', cdef="MIN")
        v_max = VDEF(vname='v0', rpn="{0},MAXIMUM".format(d_max.vname))
        v_min = VDEF(vname='v1', rpn="{0},MINIMUM".format(d_min.vname))
        l0    = LINE(1, defObj=d_max, color=color.RGBA['red'], legend="Maximum")
        l1    = LINE(1, defObj=d_min, color=color.RGBA['blue'], legend="Minimum")
        l2    = LINE(1, defObj=v_max, color=color.RGBA['red'], legend="High")
        l3    = LINE(1, defObj=v_min, color=color.RGBA['blue'], legend="Low")
        a     = AREA(defObj=d, color=color.RGBA['green'], legend="Temperature")

        for tf in self.graph_time_frames().keys():
            g = Graph(self.image_name(tf),
                      start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                      title='"Temperature - Updated {0}"'.format(time.strftime("%Y%m%d at %H:%M")),
                      vertical_label='Fahrenheit',
                      height=self.graph_height, width=self.graph_width,
                      x_grid=self.grid[tf],
                      step=self.graph_step_times[tf])
            g.data.extend([d, a])
            if self.graph_time_frames()[tf] > self.graph_time_frames()["1month"]:
                g.data.extend([d_max, d_min, v_max, v_min, l0, l1, l2, l3])
            g.write()

            if False:
                g = Graph(self.icon_name(tf),
                          start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                          no_legend=True,
                          height=self.icon_height, width=self.icon_width,
                          step=self.graph_step_times[tf])
                g.data.extend([d, a])
                g.write()

    def update(self):
        f = urllib2.urlopen('http://api.wunderground.com/api/2fa12dd9024df8dc/geolookup/conditions/q/IA/KRDU.json')
        json_string = f.read()
        parsed_json = json.loads(json_string)
        temp     = parsed_json['current_observation']['temp_f']
        humidity = parsed_json['current_observation']['relative_humidity'].rstrip('%')
        pressure = parsed_json['current_observation']['pressure_mb']
        dewpoint = parsed_json['current_observation']['dewpoint_f']
        f.close()
        self.myRRD.bufferValue(int(round(time.time())), float(temp), float(humidity), float(pressure), float(dewpoint))
        self.myRRD.update()
